/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.isfd.util;

import com.comac.ins.common.core.exception.base.BaseException;
import jep.JepException;
import jep.SharedInterpreter;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

public class ExcelDataQualityCheckUtils {
    public static final String TEMP_DIR = "tempDir";
    private static final Logger log = LoggerFactory.getLogger(PythonExecute.class);
    private static final String excelQualityCheckFileName = "excel_quality_check.py";
    static String excelQualityCheckScriptPath;
    static {
        try {
            excelQualityCheckScriptPath = saveFile(excelQualityCheckFileName);
        } catch (IOException e) {
            log.error("数据质量报告python文件生成失败", e);
            throw new BaseException("数据质量报告python文件生成失败");
        }
    }
    /**
     * excel数据质量报告
     * @param file
     * @return
     */
    public static String excelDataQualityCheck(MultipartFile file, String timeCheck, String outlierCheck){
        // 创建临时文件
        File tempDir = null;
        try {
            // 创建一个临时文件夹来存储文件
            tempDir = Files.createTempDirectory(TEMP_DIR).toFile();
        } catch (Exception e) {
            log.error("创建临时目录失败", e);
            throw new BaseException("创建临时目录失败");
        }
        String tempFilePath = tempDir +  File.separator + file.getOriginalFilename();
        File tempFile = new File(tempFilePath);
        try {
            file.transferTo(tempFile);
            // 调用Python脚本处理Excel文件
            String result =  executePythonScript(tempFilePath, timeCheck, outlierCheck);
            // 处理完文件后，删除临时文件
            if (tempFile.exists()) {
                boolean deleted = tempFile.delete();
                if (!deleted) {
                    log.error("Failed to delete the temporary file: " + tempFilePath);
                }
            }
            return result;
        } catch (IOException e) {
            log.error("创建临时文件失败", e);
            throw new BaseException("创建临时文件失败");
        }
    }

    private synchronized static String executePythonScript(String filePath, String timeCheck, String outlierCheck){

        try(SharedInterpreter jep = new SharedInterpreter()){
            log.info("python path:::"+excelQualityCheckScriptPath);
            jep.runScript(excelQualityCheckScriptPath);
            jep.set("file_path", filePath);
            jep.set("time_check", timeCheck);
            jep.set("outlier_check", outlierCheck);
            jep.eval("result = generate_excel_quality_report(file_path,time_check,outlier_check)");
            String resultString = jep.getValue("result", String.class);
            jep.close();
            return resultString;
        } catch (JepException e) {
            throw new RuntimeException(e);
        }
    }

    public static String saveFile(String fileName) throws IOException {

        InputStream is = PythonExecute.class.getClassLoader().getResourceAsStream(fileName);
        String filePath = System.getProperty("user.dir");
        String path = filePath + File.separator+ fileName;
        File file = new File(path);
        FileUtils.copyInputStreamToFile(is, file);

        return path;
    }

    public static void main() {

    }
}
